﻿using Orm.Entities;
using Scm.Jwt.Dto;
using Scm.Jwt.Util;
using Scm.Orm.Helper;
using Scm.Service.Dto;

namespace Scm.Service.Services
{
    public class UserService
    {
        public ScmUser GetUserByUsername(string username)
        {
            return SqlSugarHelper.GetDB().Queryable<ScmUser>().First(it => it.UserName == username && it.Deleted == 0);
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="Dto"></param>
        /// <returns></returns>
        public BaseDto<AccessToken> Login(LoginDto Dto, bool NeedCheckPwd = true)
        {
            if (string.IsNullOrEmpty(Dto.UserName)) return BaseDto<AccessToken>.ErrorMsg("用户名或密码不能为空");
            if (string.IsNullOrEmpty(Dto.Password)) return BaseDto<AccessToken>.ErrorMsg("用户名或密码不能为空");
            var User = GetUserByUsername(Dto.UserName);
            if (User == null) return BaseDto<AccessToken>.ErrorMsg("未匹配到用户信息");
            if (NeedCheckPwd && !CheckPassword(Dto.Password, User.Password ?? "")) return BaseDto<AccessToken>.ErrorMsg("用户名或密码不正确");
            var Token = JWTTokenUtil.GetToken(User);
            if (Token == null) return BaseDto<AccessToken>.ErrorMsg("系统异常，请稍后再试");
            return BaseDto<AccessToken>.Success(Token);
        }


        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="Dto"></param>
        /// <returns></returns>
        public BaseDto<AccessToken> Regist(RegDto Dto)
        {
            if (string.IsNullOrEmpty(Dto.UserName)) return BaseDto<AccessToken>.ErrorMsg("用户名不能为空");
            if (string.IsNullOrEmpty(Dto.Password)) return BaseDto<AccessToken>.ErrorMsg("密码不能为空");
            if (string.IsNullOrEmpty(Dto.Name)) return BaseDto<AccessToken>.ErrorMsg("用户姓名不能为空");
            if (string.IsNullOrEmpty(Dto.Mobile)) return BaseDto<AccessToken>.ErrorMsg("用户姓名不能为空");
            var User = GetUserByUsername(Dto.UserName);
            if (User != null) return BaseDto<AccessToken>.ErrorMsg("用户名已被占用");
            if (SaveUser(Dto))
            {
                var LoginDto = new LoginDto { UserName = Dto.UserName, Password = Dto.Password };
                return Login(LoginDto, false);
            }
            else
            {
                return BaseDto<AccessToken>.ErrorMsg("系统异常，请稍后再试");
            }
        }


        private bool SaveUser(RegDto Dto)
        {
            var Record = new ScmUser
            {
                Name = Dto.Name,
                UserName = Dto.UserName,
                Password = GenPassword(Dto?.Password ?? "123456"),
                Sex = Dto?.Sex ?? 1,
                Mobile = Dto?.Mobile,
                Deleted = 0,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now
            };
            var Result = SqlSugarHelper.GetDB().Insertable<ScmUser>(Record).ExecuteReturnSnowflakeId();
            return Result > 0;
        }


        /// <summary>
        /// 验证密码
        /// </summary>
        /// <param name="Password"></param>
        /// <param name="original"></param>
        /// <returns></returns>
        private bool CheckPassword(string Password, string original)
        {
            var oris = original.Split("|");
            return GenPassword(Password, oris[1]).Equals(original);
        }


        /// <summary>
        /// 创建密码
        /// </summary>
        /// <param name="Password"></param>
        /// <param name="Salt"></param>
        /// <returns></returns>
        private string GenPassword(string Password, string? Salt = null)
        {
            var SaltValue = Salt ?? StringUtil.GetRandomStr(4);
            return StringUtil.MD5String(Password + "-" + SaltValue) + "|" + SaltValue;
        }

    }
}